package org.oslo.sessioninfo.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;

import org.oslo.sessioninfo.domain.SessionInfo;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class XMLReader {
	
	private static String xmlString;
	
	public static ArrayList<SessionInfo> getSessionInfo(String conferenceName) throws Exception {
		ArrayList<SessionInfo> sessionList = new ArrayList<SessionInfo>();
		if(xmlString == null) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					Thread.currentThread().getContextClassLoader().getResourceAsStream("sessions.xml")));
			xmlString = "";
			while(reader.ready()) {
				xmlString += reader.readLine();
			}
			System.out.println("xml " + xmlString);
		}
		NodeList sessionNodeList = executeXPath(xmlString, "//conference[@name='" + conferenceName + "']//session");
		System.out.println("list size " + sessionNodeList.getLength());
		for(int i = 0; i < sessionNodeList.getLength(); i++) {
			Node sessionNode = sessionNodeList.item(i);
			SessionInfo sessionInfo = createSessionInfo(sessionNode);
			sessionList.add(sessionInfo);
		}
		return sessionList;
	}
	
	private static NodeList executeXPath(String input, String xpath) {
        NodeList result = null;
        try {
            XPath path = javax.xml.xpath.XPathFactory.newInstance().newXPath();
            result = (NodeList) path.evaluate(xpath, new InputSource(new StringReader(input)),
            		XPathConstants.NODESET);
        } catch (XPathExpressionException ex) {
            ex.printStackTrace();
            Logger.getLogger("global").log(Level.SEVERE, null, ex);
        }
        
        return result;   
    }
	
	private static SessionInfo createSessionInfo(Node sessionNode) {
		NodeList sessionInfoList = sessionNode.getChildNodes();
		SessionInfo sessionInfo = new SessionInfo();
		for(int i = 0; i < sessionInfoList.getLength(); i++) {
			Node sessionInfoNode = sessionInfoList.item(i);
			String infoName = sessionInfoNode.getLocalName();
			String infoValue = sessionInfoNode.getTextContent();
			if("day".equals(infoName)) {
				sessionInfo.setDay(infoValue);
			} else if("starttime".equals(infoName)) {
				sessionInfo.setStartTime(infoValue);
			} else if("endtime".equals(infoName)) {
				sessionInfo.setEndTime(infoValue);
			} else if("speakername".equals(infoName)) {
				sessionInfo.setSpeakerName(infoValue);
			} else if("title".equals(infoName)) {
				sessionInfo.setTitle(infoValue);
			} else if("description".equals(infoName)) {
				sessionInfo.setDescription(infoValue);
			}
		}
		return sessionInfo;
	}

}
